package com.fengwk.support.util;

import java.lang.reflect.Field;

import com.fengwk.support.exception.BaseException;
import com.fengwk.support.util.LoggerUtils.Logger;

import sun.misc.Unsafe;

@SuppressWarnings("restriction")
public class UnsafeUtils {

    private static final Logger LOG = LoggerUtils.getLogger(UnsafeUtils.class);
    
    private static final String THE_UNSAFE = "theUnsafe";
    
    private UnsafeUtils() {
        throw new BaseException("can not instance " + getClass());
    }
    
    public static Unsafe getUnsafe() {
        Unsafe unsafe = null;
        Class<?> unsafeClass = Unsafe.class;
        for (Field f : unsafeClass.getDeclaredFields()) {
            if (THE_UNSAFE.equals(f.getName())) {
                f.setAccessible(true);
                try {
                    unsafe = (Unsafe) f.get(null);
                    break;
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    LOG.error(e);
                }
            }
        }
        if (unsafe == null)
            throw new BaseException("getUnsafe fail");
        return unsafe;
    }
    
}
